/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var PokerRoom = require('../Poker/room').PokerRoom;

var Const = require('./const');
var SubCode = require('../subCode');

var RoundStatus = {
    'WAITING': 1,   // 等待其它玩家准备
    'SELECTBASE': 2, //设置了基础分
    'READY': 3,     // 就绪，开始游戏
    'PLAY': 4,     // 玩家选牌
}

exports.WNNNRoom = PokerRoom.extend({
    _roundStatus: RoundStatus.WAITING,

    _dealerIndex: 0,           // 庄家坐位
    _selectWaitTime: 0,        // 开始选牌的时间

    init: function (rid, creator, msg) {
        msg.options.roomPlayerNum = msg.options.playersNum;
        this._super(rid, creator, msg);

        this._roundStatus = RoundStatus.WAITING;

        this.selectedBase = false;
        this.selected = false;

        this.selectedBaseID = 0;
        this.selectedID = 0;

        this.selectBaseTime = 0;
        this.selectTime = 0;

        this._dealerIndex = 0;
        this.MSMode = null;
        var MS = this.getOption("dealerRule");
        if (MS == 1) {
            this.MSMode = "LLZZ";
        } else if (MS == 2) {
            this.MSMode = "SJZZ";
        } else if (MS == 3) {
            this.MSMode = "BZ";
        }

        this.playStyle = false;
        if (this.getOption("playStyle")) {
            this.playStyle = true;
        }
        // if (this.getOption("MS") == "FZZ") {
        //     this._dealerIndex = 1;
        // } else {
        //     this._dealerIndex = 0;
        // }

        this._selectWaitTime = 0;


    },
    reset: function () {
        this.selectedBase = false;
        this.selected = false;

        this.selectBaseTime = 0;
        this.selectTime = 0;
        clearTimeout(this.selectedID)
        clearTimeout(this.selectedBaseID)
    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function () {
        var info = this._super();
        // info.robDealerWaitMS = this.getHideOption("robDealerWaitMS");
        // info.selectWaitMS = this.getHideOption("selectWaitMS");
        return info;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.dealer = this._dealerIndex;

        if (this.selectTime) {
            info.remainBaseTime = 0;
            info.remainSelectTime = this.getHideOption("selectWaitMS") - (Date.parse(new Date()) - this.selectTime);
        } else {
            info.remainBaseTime = this.getHideOption("selectBaseScoreWaitMS") - (Date.parse(new Date()) - this.selectBaseTime);
            info.remainSelectTime = this.getHideOption("selectWaitMS") - (Date.parse(new Date()) - this.selectTime);
        }

        return info;
    },

    onAfterPlayerReady: function (player) {
        this._super(player);

        var subConfig = this.getSubConfig();
        //检查是否开始游戏
        
        if (!this.isPlaying() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin
            && this.getPlayerCount() == this.getReadyPlayerCount()) {
            //&& this.getPlayerCount() == this.getOption("playersNum")
            //this._startNewRoundAfter(this.getHideOption("startWaitMS"));
            this._roundStatus = RoundStatus.READY;
            console.log("starttting")


        }
    },

    checkStartNewRound: function () {
        if (this.isPlaying()) {
            return false;
        }

        if (this._roundStatus != RoundStatus.READY) {
            return false;
        }

        return true;
    },
    //1
    onBeforeStartNewRound: function () {
        this._super();
        this._selectWaitTime = 0;
    },
    //2
    onAfterStartNewRound: function () {
        this._super();
        this._startPlay();
    },

    onSettlement: function () {
        this._super();

        this.enumPlaying(function (eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });
    },


    getRoomConfig: function () {
        var cfg = this._super();
        //cfg.destroyWaitTime = 200;
        //cfg.respDestroyIgnore = 1;
        cfg.resetDestroyOnNewRound = 0;
        return cfg;
    },
    onCurRoundFinished: function () {
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        this.reset();
        // if (this.MSMode == "LLZZ") {
        //     this._dealerIndex = this.getNextPlayer(this._dealerIndex);
        // }
        // this.broadcastReplay("onDealerChanged", {
        //     dealer: this._dealerIndex,
        // });
    },
    onDestroy: function () {
        clearTimeout(this.selectedID)
        clearTimeout(this.selectedBaseID)
    },


    /******************************************************************
     * 功能接口
     ******************************************************************/


    handleSelectBaseScore: function (player, msg, callback) {
        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (player.getBaseScore() != 0) {
            callback({ code: SubCode.TASK_UNMATCHED }); return;
        }

        if (!msg.hasOwnProperty('score') || isNaN(msg.score)) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        var score = parseInt(msg.score);
        if (score != 1 && score != 2 && score != 3) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }

        player.setBaseScore(score);
        this.broadcast("onPlayerBaseScore", {
            playerIndex: player.getIndex(),
            baseScore: score
        });
        callback({});

        var isAllSet = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isDealer() && ePlayer.getBaseScore() == 0) {
                isAllSet = false;
            }
        });

        if (isAllSet) {
            this._dealSelectedBase();
        }
    },

    handleSelectCards: function (player, msg, callback) {
        if (!msg.cards) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        if (!player.isPlaying()) {
            callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        }

        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.isCurRoundFinished()) {
            callback({ code: Code.ROOM_ROUND_FINISHED }); return;
        }

        var cards = msg.cards;
        if (!ExObject.isArray(cards)) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }

        if (!player.setSelectedCards(cards)) {
            callback({ code: SubCode.CARD_NOT_EXIST }); return;
        }

        callback({});

        this.broadcast("onPlayerSelectCards", {
            playerIndex: player.getIndex(),
            selectCards: cards.slice()
        });
        player.isSelected = true;

        var isAllSelected = true;
        this.enumPlaying(function (eIndex, ePlayer) {
            if (!ePlayer.isSelectedCards()) {
                isAllSelected = false;
            }
        });

        if (isAllSelected && this.selected == false) {
            this.selected = true;
            this.settlementCurRound();
        }
    },

    _startPlay: function () {
        //this.initPlayersHandCards();
        if (this.MSMode == "LLZZ") {
            if (this._dealerIndex == 0) {
                this._dealerIndex = 1;
                this.broadcastReplay("onDealerChanged", {
                    dealer: this._dealerIndex,
                });
            } else {
                this._dealerIndex = this.getNextPlayer(this._dealerIndex);
                this.broadcastReplay("onDealerChanged", {
                    dealer: this._dealerIndex,
                });
            }
            this.getPlayerByIndex(this._dealerIndex).setBaseScore(1);
            this._waitSelectBaseScore();
        } else if (this.MSMode == "SJZZ") {
            var arr = [];
            this.enumPlaying(function (eIndex, ePlayer) {
                arr.push(eIndex);
            });
            this._dealerIndex = Ext.randArray(arr)
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
            this.getPlayerByIndex(this._dealerIndex).setBaseScore(1);
            this._waitSelectBaseScore();
        } else if (this.MSMode == "BZ") {
            if (this._dealerIndex == 0) {
                this._dealerIndex = 1;
                this.broadcastReplay("onDealerChanged", {
                    dealer: this._dealerIndex,
                });
            }
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });

            this.getPlayerByIndex(this._dealerIndex).setBaseScore(1);
            this._waitSelectBaseScore();
        }
    },
    _dealSelectedBase: function () {
        if (this.selectedBase == false) {
            this.selectedBase = true;

            this.initPlayersHandCards();
            this._waitSelectCards();
        }
        return;
    },

    _waitSelectCards: function () {

        this._roundStatus = RoundStatus.PLAY;
        this._selectWaitTime = Date.getStamp();

        this.broadcast("onWaitSelect", {
            "waitTime": this.getHideOption("selectWaitMS")
        });
        this.selectTime = Date.parse(new Date());
        this.selectedID = setTimeout(function () {
            if (this.selected)
                return;
            this.selected = true;
            this.settlementCurRound();
        }.bind(this), this.getHideOption("selectWaitMS")+1000);
    },

    _waitSelectBaseScore: function () {
        this.broadcast("onWaitBaseScore", {
            "waitTime": this.getHideOption("selectBaseScoreWaitMS"),
        });
        this.selectBaseTime = Date.parse(new Date());
        this.selectedBaseID = setTimeout(function () {
            if (!this.isPlaying()) {
                return;
            }

            if (this._roundStatus != RoundStatus.READY) {
                return;
            }

            this.enumPlaying(function (eIndex, ePlayer) {
                if (ePlayer.getBaseScore() == 0) {
                    ePlayer.setBaseScore(1);
                    this.broadcast("onPlayerBaseScore", {
                        playerIndex: ePlayer.getIndex(),
                        baseScore: ePlayer.getBaseScore()
                    });
                }
            }.bind(this));
            this._dealSelectedBase();
            //this._dealRobDealerAllSet();

        }.bind(this), this.getHideOption("selectBaseScoreWaitMS")+4000);
    },

});